package com.haixee.parkdemo.auth.controller;

import com.haixee.parkdemo.auth.entity.vo.AclTreeVO;
import com.haixee.parkdemo.auth.model.Acl;
import com.haixee.parkdemo.auth.service.AclService;
import com.haixee.parkdemo.common.response.ResResult;
import com.haixee.parkdemo.common.response.ResUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("acl")
public class AclController {

    @Autowired
    private AclService aclService;

    @PostMapping("/add")
    public ResResult addAcl(@RequestBody Acl acl) {

        aclService.addAcl(acl.getParentId(), acl.getName(), acl.getIsModule(), acl.getMethod(), acl.getRouter(), acl.getIsOpen());
        return ResUtil.success();
    }

    @GetMapping("/all")
    public ResResult getTree() {
        List<Acl> aclList = aclService.selectAll();

        Map<Integer, AclTreeVO> map = new HashMap<>();
        AclTreeVO theVO = new AclTreeVO();
        map.put(0, theVO);

        List<AclTreeVO> unmount = new ArrayList<>();

        for (Acl acl : aclList) {
            AclTreeVO vo = new AclTreeVO();
            vo.setId(acl.getId());
            vo.setParentId(acl.getParentId());
            vo.setName(acl.getName());
            vo.setMethod(acl.getMethod());
            vo.setRouter(acl.getRouter());
            vo.setOpen(acl.getIsOpen());
            vo.setModule(acl.getIsModule());

            map.put(vo.getId(), vo);

            AclTreeVO parentVO = map.get(vo.getParentId());
            if (parentVO != null) {
                parentVO.getChildren().add(vo);
            } else {
                unmount.add(vo);
            }
        }

        for (AclTreeVO aclTreeVO : unmount) {
            map.get(aclTreeVO.getParentId()).getChildren().add(aclTreeVO);
        }

        return ResUtil.success(theVO.getChildren());
    }
}
